<?php

require_once '/config/config.php';

class DB {

    static $_connection;
    PUBLIC $QUERY_SELECT = 0;
    public $QUERY_INSERT = 1;
    
    public static function getConnection() {
        if (!isset(self::$_connection)) {
            self::$_connection = mysql_connect(DB_HOST . ":" . DB_PORT, DB_USER, DB_PASS) or die(mysql_error());
            mysql_select_db(DB_NAME, self::$_connection);
        }
        return self::$_connection;
    }

    public static function escape($string) {
        return mysql_real_escape_string($string);
    }

    public static function escapeArr($arr) {
        if (empty($arr))
            return $arr;
        foreach ($arr as $key => $value) {
            $arr[$key] = $this->escape($value);
        }
        return $arr;
    }

    public function query($query, $type=NULL) {
        mysql_query('SET NAMES utf8', self::getConnection());
        $ret = mysql_query($query, self::$_connection);
        if ($ret == null) {
            echo "MYSQL QUERY: $query\n";
            echo "MYSQL ERROR: ";
            print_r(mysql_error(self::$_connection));
            echo "\n";
            die();
        }
        switch ($type){
            case $this->QUERY_INSERT:
                return mysql_insert_id();
            default:
                return $ret;
        }
    }
}